/**
 * 
 */
package com.moyq5.mvcmaker;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.moyq5.mvcmaker.impl.DaoImplMvcMaker;
import com.moyq5.mvcmaker.impl.DaoMvcMaker;
import com.moyq5.mvcmaker.impl.FormMvcMaker;
import com.moyq5.mvcmaker.impl.JacksonFilterMvcMaker;
import com.moyq5.mvcmaker.impl.JacksonMixInFactoryMvcMaker;
import com.moyq5.mvcmaker.impl.JacksonMixinMvcMaker;
import com.moyq5.mvcmaker.impl.SearchMvcMaker;
import com.moyq5.mvcmaker.impl.ServiceImplMvcMaker;
import com.moyq5.mvcmaker.impl.ServiceMvcMaker;

/**
 * @author Moyq5
 * @date 2016年9月27日
 */
public class MvcMakerFactory {
	
	public static void execute(Project pj) throws Exception {
		BeanModule bm = pj.beanModule();
		ServiceModule sm = pj.serviceModule();
		List<WebModule> webs = pj.webModules();
		
		MvcMaker searchMk = new SearchMvcMaker(bm);
		MvcMaker daoMk = new DaoMvcMaker(sm);
		MvcMaker daoImplMk = new DaoImplMvcMaker(sm);
		MvcMaker serviceMk = new ServiceMvcMaker(sm);
		MvcMaker serviceImplMk = new ServiceImplMvcMaker(sm);
		
		List<String> entityNames = getEntityNames(bm);
		entityNames.forEach(name -> {
			try {
				searchMk.execute(name);
				daoMk.execute(name);
				daoImplMk.execute(name);
				serviceMk.execute(name);
				serviceImplMk.execute(name);
			} catch (Exception e) {
				e.printStackTrace();
			}
			webs.forEach(wm -> {
				MvcMaker mixInMk = new JacksonMixinMvcMaker(wm);
				MvcMaker filterMk = new JacksonFilterMvcMaker(wm);
				MvcMaker formMk = new FormMvcMaker(wm);
				try {
					mixInMk.execute(name);
					filterMk.execute(name);
					formMk.execute(name);
				} catch (Exception e) {
					e.printStackTrace();
				}
			});
		});
	}
	
	public static void updateMixInFactory(Project pj) {
		BeanModule bm = pj.beanModule();
		List<WebModule> webs = pj.webModules();
		List<String> entityNames = getEntityNames(bm);
		webs.forEach(wm -> {
			try {
				new JacksonMixInFactoryMvcMaker(wm).execute(entityNames);
			} catch (Exception e) {
				e.printStackTrace();
			}
		});
	}

	private static List<String> getEntityNames(BeanModule module) {
		String filePath = module.getPath() + File.separator
				+ (module.getEntityPackage().replace(".", File.separator));
		File entityDir = new File(filePath);
		String[] fileNames = entityDir.list();
		List<String> entityNames = new ArrayList<String>();
		for (String fileName : fileNames) {
			entityNames.add(fileName.replace(".java", ""));
		}
		return entityNames;
	}
}
